package com.google.jessewilson.codesearch.intellij;

import com.google.inject.Inject;
import com.google.jessewilson.codesearch.api.Query;
import com.google.jessewilson.codesearch.api.QueryRunner;
import com.google.jessewilson.codesearch.ui.preflight.PreflightQueryEditor;

import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogBuilder;
import com.intellij.openapi.ui.DialogWrapper;

import java.awt.event.ActionEvent;

import javax.swing.*;

/**
 * IntelliJ dialog box for the preflight query editor.
 * 
 * @author jessewilson
 */
class PreflightQueryEditorDialog {

  private final QueryRunner queryRunner;
  private final Project project;
  private final PreflightQueryEditor preflightQueryEditor;

  @Inject
  public PreflightQueryEditorDialog(QueryRunner queryRunner,
      Project project, PreflightQueryEditor preflightQueryEditor) {
    this.queryRunner = queryRunner;
    this.project = project;
    this.preflightQueryEditor = preflightQueryEditor;
  }

  /**
   * Creates and displays the preflight query editor dialog.
   */
  void show(Query query) {
    preflightQueryEditor.setValue(query);

    // build a dialog to show the query panel
    final DialogBuilder dialogBuilder = new DialogBuilder(project);
    dialogBuilder.setTitle("Code Search");
    dialogBuilder.setCenterPanel(preflightQueryEditor.getComponent());

    // build an action to kick off the query
    AbstractAction queryAction = new AbstractAction("Search") {
      public void actionPerformed(ActionEvent e) {
        Query preparedQuery = preflightQueryEditor.getValue();
        queryRunner.query(preparedQuery, preflightQueryEditor.getActiveProvider());
        dialogBuilder.getDialogWrapper().close(DialogWrapper.OK_EXIT_CODE);
      }
    };

    // tell the dialog and query panel about the action
    dialogBuilder.addAction(queryAction);
    preflightQueryEditor.setAction(queryAction);

    // add the cancel action last, so it's after the 'ok' action
    dialogBuilder.addCancelAction();

    // show the dialog
    dialogBuilder.showModal(true);
  }
}